package top.went.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.stylesheets.LinkStyle;
import top.went.exception.InputException;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.*;
import top.went.service.*;
import top.went.utils.CheckForm;
import top.went.vo.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/sale")
@ResponseBody
public class PurchaseController {
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private UserService userService;
    @Autowired
    private PlanPayDetailService planPayDetailService;
    @Autowired
    private PurchaseReceiptService purchaseReceiptService;
    @Autowired
    private PayRecordsService payRecordsService;
    @Autowired
    private WareHouseService wareHouseService;
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private ReturnGoodsDetailService returnGoodsDetailService;
    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Autowired
    private ApprovalService approvalService;
    @GetMapping("/mainPurchase")
    public ModelAndView mainPurchase(String mark) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("sale/MainPurchase");
        mv.addObject("mark", mark);
        return mv;
    }

    @GetMapping("/purAddModal")
    public ModelAndView modal() {
        ModelAndView mv = new ModelAndView();
        try {
            List<UserEntity> userEntityList = userService.queryAllUser(1, 10).getRows();
            mv.addObject("userEntityList", userEntityList);
            mv.setViewName("sale/modal/add_pur_model");
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return mv;
    }

    @GetMapping("/purQueryModal")
    public ModelAndView purQueryModal() {
        return new ModelAndView("sale/modal/pur_super_query_model");
    }

    @GetMapping("/purDetail")
    public ModelAndView purDetail() {
        return new ModelAndView("sale/purchaseDetail");
    }

    /**
     * 添加采购单
     *
     * @param purchaseEntity
     * @throws ServiceException
     */
    @PostMapping("/pur_insert")
    @ResponseBody
    public Code pur_insert(PurchaseEntity purchaseEntity) throws ServiceException {
        purchaseEntity.setMagicDelete(0l);
        purchaseEntity.setPurState("新采购");
        if (purchaseService.pur_insert(purchaseEntity) != null && purchaseService.pur_insert(purchaseEntity).toString().length() > 0) {
            int a = purchaseService.pur_insert(purchaseEntity);
            return Code.success(a + "");
        }
        return Code.fail();
    }

    /**
     * 删除采购单
     *
     * @param purId
     * @throws ServiceException
     */
    @PostMapping("/purdelete")
    @ResponseBody
    public Code pur_delete(Integer purId) throws ServiceException {
        try {
            if (purchaseService.pur_logicDelete(purId))
                return Code.success("删除采购单成功");
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return Code.fail();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     * @throws InputException
     * @throws NotFoundException
     * @throws ServiceException
     */
    @RequestMapping("/purdeleteall")
    @ResponseBody
    public Code deleteAll(@RequestParam(value = "ids[]") Long[] ids) throws InputException, NotFoundException, ServiceException {
        for (int i = 0; i < ids.length; i++)
            if (ids[i] == null || ids[i].toString().length() <= 0)
                throw new InputException("id错误");
        purchaseService.pur_logicDeleteAll(ids);
        return Code.success("批量删除成功");
    }

    /**
     * 查询所有采购单
     *
     * @return
     * @throws ServiceException
     */
    @PostMapping("/purfindAll")
    @ResponseBody
    public PageEntity<PurchaseVO> findAll(@RequestBody top.went.vo.Page page) throws ServiceException {
        return purchaseService.pur_findAll(page.getSize(), page.getPage());
    }

    /**
     * 加载
     *
     * @param purId
     * @return
     */
    @GetMapping("purload")
    @ResponseBody
    public Code load(Integer purId) {
        PurchaseVO purchaseVO = null;
        try {
            purchaseVO = purchaseService.load1(purId);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return Code.success(purchaseVO);
    }

    /**
     * 加载所有
     *
     * @return
     */
    @RequestMapping("/purall")
    public PageEntity<PurchaseEntity> loadAll(@RequestBody PurchaseVO purchaseVO) {
        return purchaseService.findAllByManyConditions(purchaseVO);
    }

    /**
     * 查看详情
     *
     * @param purId
     * @return
     */
    @RequestMapping("/purdetail1/{purId}/")
    public ModelAndView detail(@PathVariable("purId") int purId) throws NotFoundException, ServiceException {
        return getMV(purId);
    }

    /**
     * 采购详情页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/purProDetail/{id}/")
    public ModelAndView detailInfo(@PathVariable("id") Long id) {
        return getModelAndView(id, "404", "sale/purchaseProDetail");
    }

    /**
     * 加载采购明细数据
     *
     * @param id
     * @return
     * @throws InputException
     */
    @RequestMapping("/purProDetail1")
    @ResponseBody
    public List<PurchaseDetailVO> loadDeatil(Long id) throws InputException {
        if (id == null || id.toString().length() <= 0)
            throw new InputException("信息错误");
        return purchaseService.loadDeatil(id);
    }

    /**
     * 加载采购明细数据
     *
     * @param id
     * @return
     * @throws InputException
     */
    @RequestMapping("/purProDetail2")
    @ResponseBody
    public List<PurchaseDetailVO> loadDeatil1(Long id) throws InputException {
        if (id == null || id.toString().length() <= 0)
            throw new InputException("信息错误");
        List<PurchaseDetailVO> list = purchaseService.loadDeatil(id);
        List<PurchaseDetailVO> list1 = new ArrayList<>();
        for (PurchaseDetailVO purchaseDetailVO : list) {
            if (purchaseDetailVO.getPdWpNum() != 0) {
                list1.add(purchaseDetailVO);
            }
        }
        return list1;
    }

    /**
     * 返回采购状态
     *
     * @param id
     * @return
     * @throws InputException
     * @throws NotFoundException
     */
    @RequestMapping("/purProDetail111")
    @ResponseBody
    public Code loadDeatil111(Long id) throws InputException, NotFoundException {
        if (id == null || id.toString().length() <= 0)
            throw new InputException("信息错误");
        List<PurchaseDetailVO> list = purchaseService.loadDeatil(id);
        PurchaseEntity purchaseEntity = purchaseService.load(Math.toIntExact(id));
        String state = purchaseEntity.getPurState();
        if (list.size() > 0 && (state.equals("部分入库") || state.equals("入库完成"))) {
            return Code.success(1);
        }
        if (list.size() > 0 && (state.equals("新采购") || state.equals("生成入库单"))) {
            return Code.success(2);
        }
        if (list.size() < 0) {
            return Code.success(3);
        }
        return Code.success(4);
    }

    /**
     * 保存采购明细数据
     *
     * @param purchaseDetailVO1
     * @return
     */
    @PostMapping("/purdetail/save")
    public Code saveDetail(PurchaseDetailVO1 purchaseDetailVO1) throws InputException, NotFoundException, ServiceException {
        if (purchaseDetailVO1.getId() == null)
            throw new InputException("采购单信息错误");
        List<PurDetailEntity> purDetailEntities = purchaseDetailVO1.getDatas();
        purchaseService.addDetail(purDetailEntities, purchaseDetailVO1.getId());
        return Code.success();
    }

    /**
     * 根据客户id选择采购单
     *
     * @param
     * @return
     */
    @GetMapping("/choosePur")
    public Code saveDetail1(Integer cusId) throws InputException, NotFoundException, ServiceException {
        PurchaseVO purchaseVO = new PurchaseVO();
        purchaseVO.setCusId(cusId);
        List<PurchaseEntity> purchaseEntities = purchaseService.findAllByManyConditions(purchaseVO).getRows();
        return Code.success(purchaseEntities);
    }

    private ModelAndView getModelAndView(@PathVariable("id") Long id, String s, String s1) {
        ModelAndView modelAndView = new ModelAndView();
        if (id == null)
            return new ModelAndView("404");
        try {
            PurchaseVO purchaseVO = purchaseService.load1(Math.toIntExact(id));
            if (purchaseVO == null)
                return new ModelAndView("404");
            modelAndView.addObject("info", purchaseVO);
            modelAndView.setViewName(s1);
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("404");
        }
        return modelAndView;
    }


    private ModelAndView getMV(Integer purId) throws NotFoundException, ServiceException {
        if (new Integer(purId) == null) 
            return new ModelAndView("404");
        ModelAndView mv = new ModelAndView("sale/purchaseDetail");
        PurchaseEntity purchaseEntity = purchaseService.load(purId);
        if (purchaseEntity == null)
            return new ModelAndView("404");
        List<ReturnGoodsVO> returnGoodsVOS = returnGoodsService.findAll(new ReturnGoodsVO(purId)).getRows();
        String rgIds = "";
        for (ReturnGoodsVO returnGoodsVO1 : returnGoodsVOS) {
            Integer rgId = returnGoodsVO1.getRgId();
            rgIds = rgIds + rgId + ",";
        }
        if (rgIds.length() > 1) {
            rgIds = rgIds.substring(0, rgIds.length() - 1);
        }
        purchaseEntity.setPurState(purchaseService.getState(purId).getPurState());
        List<PlanPayDetailEntity> planPayDetailEntityPage = planPayDetailService.findAllByManyConditions(new PlanPayDetailVO(purId)).getRows();
        List<PurchaseReceiptEntity> purchaseReceiptEntitylist = purchaseReceiptService.findAllByManyConditions(new PurchaseReceiptVO(purId)).getRows();
        List<PaymentRecordsEntity> paymentRecordsEntities = payRecordsService.findAllByManyConditions(new PaymentRecordVO(purId)).getRows();
        mv.addObject("approvals",approvalService.findApprovalById(purId,"采购"));
        mv.addObject("rgIds", rgIds);
        mv.addObject("info", purchaseEntity);
        mv.addObject("purchaseReceiptEntitylist", purchaseReceiptEntitylist);
        mv.addObject("planPayDetailEntityPage", planPayDetailEntityPage);
        mv.addObject("paymentRecordsEntities", paymentRecordsEntities);
        mv.addObject("returnGoodsVOS", returnGoodsVOS);
        return mv;
    }
}
